package edu.ruc.cluster.action;

import java.io.IOException;

import edu.ruc.cluster.util.AbstractInteractiveCommand;
import edu.ruc.cluster.util.Const;
import edu.ruc.cluster.util.PropertyRetrieval;

/**
 * 2012-12-29
 * Used: UnTar the Const.HADOOP_JDK_FILE in sudoer's home folder of each machine
 * 		 Move it to Const.HADOOP_DST_TAG in Const.CONFIG_FILE
 * 		 chown -R addUser.addUser /home/addUser
 * @author deke
 */
public class ConfigHadoopCmd extends AbstractInteractiveCommand {
 
	public ConfigHadoopCmd(String host, String passwd){
		super(host, passwd);
	}
	@Override
	public void interactProcess(String cmd) {
		// TODO Auto-generated method stub
		String[] commands = cmd.split("xxx");
		try{
			int count = 1;
			for(int i = 0 ; i < commands.length; i ++){
				writor.write((commands[i]+ "\n").getBytes());
				writor.flush();
							
		    	char[] cbuf = new char[1024];			
				int ret = reader.read(cbuf);
				
				while(ret != -1){
					String info = new String(cbuf, 0, ret);
					System.out.print(info);
					
					if(info.contains("[" + getUser()+ "@" )){	
//					if(info.contains("@" + getHost())){
						if(count == 0){
							break;
						}
						count --;
					}else if(info.contains("password")){
						writor.write((getPasswd() + "\n").getBytes());
						writor.flush();
					}
					ret = reader.read(cbuf);
				}
			}
			
		}catch(IOException e){
			logHandler.error(this.getClass().getSimpleName() + e.getMessage(), e);
		}
		
	}
	public void confhadoop(){
		PropertyRetrieval pr = new PropertyRetrieval(Const.CONFIG_FILE);
		String addUser = pr.getString(Const.HADOOP_USER_TAG);
		String hadoopdst = "/home/" + addUser + "/" + pr.getString(Const.HADOOP_DST_TAG);
//		if(hadoopdst.charAt(hadoopdst.length() - 1) == '/')
//			hadoopdst = hadoopdst.substring(0, hadoopdst.length() - 1);
//		String binfile = hadoopdst + "/" + pr.getString(Const.HADOOP_FOLDER_TAG) + "/bin/";
//		binfile = binfile.replaceAll("//", "/");
		String cmd1 = "sudo mkdir -p " + hadoopdst;
		String cmd2 = "sudo tar -zxf " + Const.HADOOP_TAR_FILE + " -C " + hadoopdst;
		String cmd3 = "sudo chown -R " + addUser + "." + addUser + " " + "/home/" + addUser ;
//		String cmd4 = "chmod +x " + binfile + "*"; 
		dealcmd(cmd1 + "xxx" + cmd2 + "xxx" + cmd3 );		
	}
	
	/*
	public static void main(String[] args){
		String host = "deke@dlnode27";
		String passwd = "111111";
		ConfigHadoopCmd lc = new ConfigHadoopCmd(host, passwd);
		lc.confhadoop();
	}
	*/
}
